package com.zzn.bookManage.controller;

import com.zzn.bookManage.pojo.Book;
import com.zzn.bookManage.pojo.ResultEntity;
import com.zzn.bookManage.pojo.User;
import com.zzn.bookManage.service.BookService;
import com.zzn.bookManage.service.UserService;
import com.zzn.bookManage.util.ObjectHolder;
import com.zzn.bookManage.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 列出图书信息
 */

@WebServlet("/listBorrow")
public class ListBorrowBooks extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(true); // 必定获得一个session
        User loginUser = (User) session.getAttribute("loginUser");
        boolean isAdmin = "admin".equals(loginUser.getUsername());

        String pageStr = req.getParameter("page");
        // 消息传递
        String msg = req.getParameter("msg");
        int page = 1;
        int row  = 10;

        if (StringUtil.notBlank(pageStr)){
            page = Integer.parseInt(pageStr);
        }

        BookService bookService = ObjectHolder.getInstance().getBookService();
        UserService userService = ObjectHolder.getInstance().getUserService();


        ResultEntity<Book> resultEntity ;
        if (isAdmin){
            resultEntity = bookService.listBooks(page, row);
        }else {
            resultEntity = bookService.listBorrowBooks(loginUser.getUid(), page, row);
        }

        List<User> users = userService.listUsers();
        users = users.stream().filter(a->!"admin".equals(a.getUsername())).collect(Collectors.toList());

        if (resultEntity.hasData()){
            // 查询成功
            req.setAttribute("msg",msg);
            req.setAttribute("result",resultEntity);
            req.setAttribute("users",users);
            if (isAdmin){
                req.getRequestDispatcher("/borrowMain.jsp").forward(req, resp);
            }else{
                req.setAttribute("msg","没有权限");
                req.getRequestDispatcher("/userMain.jsp").forward(req, resp);
            }
        }else{
            // 查询失败
            req.setAttribute("result",resultEntity);
            req.setAttribute("msg","没有记录");
            if (isAdmin){
                req.getRequestDispatcher("/borrowMain.jsp").forward(req, resp);
            }else{
                req.setAttribute("msg","没有权限");
                req.getRequestDispatcher("/userMain.jsp").forward(req, resp);
            }
        }
    }
}
